import { _decorator, assetManager, AssetManager, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('HelloWorld')
export class HelloWorld extends Component {
    async start() {
        for (let i = 1; i <= 100; i++) {
            await this.sleep(i);
            console.log(`第${i}步`);
        }

        // await this.sleep(2);
        // console.log('第2步');
        // await this.sleep(3);
        // console.log('第3步');
        // await this.sleep(4);
        // console.log('第4步');

        // this.delay(1, () => {
        //     console.log('第1步');
        //     this.delay(2, () => {
        //         console.log('第2步');
        //         this.delay(3, () => {
        //             console.log('第3步');
        //             this.delay(4, () => {
        //                 console.log('第4步');
        //             })
        //         })
        //     })
        // })
    }

    delay(duration: number, callback: () => void): void {
        this.scheduleOnce(callback, duration);
    }
    
    sleep(duration: number): Promise<void> {
        return new Promise<void>((resolve) => {
            this.scheduleOnce(resolve, duration);
        });
    }

    loadAsset(path: string, type: any, callback: (asset: any) => void): void {
        let id = path.indexOf('/');
        let bundleName = path.slice(0, id);
        let assetPath = path.slice(id + 1);
        assetManager.loadBundle(bundleName, (err: Error, bundle: AssetManager.Bundle) => {
            if (err) { callback(null); return; }
            bundle.load(assetPath, type, (err: Error, asset: any): void => {
                callback(err ? null : asset);
            });
        });
    }
}